package com.xdwanj.servlet;

import com.mysql.jdbc.StringUtils;
import com.xdwanj.pojo.*;
import com.xdwanj.service.*;
import com.xdwanj.service.impl.*;
import com.xdwanj.util.ConstantsRes;
import com.xdwanj.util.ConstantsVal;
import com.xdwanj.util.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/admin")
public class AdminUserServlet extends HttpServlet {

    /**
     * 根目录
     */
    public static final String REQUEST_MAPPING = "admin";
    /**
     * 方法属性名
     */
    public static final String METHOD = "method";

    /**
     * 标记位
     */
    public static final String MARK_FUN = "markFun";

    /**
     * 寻找用户名方法
     */
    public static final String FIND_USER = "findUser";

    /**
     * 更新用户
     */
    public static final String UPDATE_USER = "updateUser";

    /**
     * 添加用户
     */
    public static final String ADD_USER = "addUser";

    /**
     * 删除用户
     */
    public static final String DELETE_USER = "deleteUser";

    /**
     * 用户ID
     */
    public static final String UID = "uid";

    /**
     * 用户姓名
     */
    public static final String USER_NAME = "username";

    /**
     * 用户昵称
     */
    public static final String NAME = "name";

    /**
     * 用户密码
     */
    public static final String PASSWORD = "password";

    /**
     * 用户性别
     */
    public static final String SEX = "sex";

    /**
     * 邮箱
     */
    public static final String EMAIL = "email";

    /**
     * 用户电话
     */
    public static final String PHONE = "phone";

    /**
     * 注册日期
     */
    public static final String REGISTER_DATE = "registerDate";

    /**
     * 地址
     */
    public static final String ADDRESS = "address";

    /**
     * 生日
     */
    public static final String BIRTHDAY = "birthday";

    /**
     * 头像
     */
    public static final String IMAGE = "image";

    /**
     * 用户列表
     */
    public static final String USER_LIST = "userList";

    /**
     * 查宠物
     */
    public static final String FIND_PET = "findPet";

    /**
     * 更新宠物
     */
    public static final String UPDATE_PET = "updatePet";

    /**
     * 删除宠物
     */
    public static final String DELETE_PET = "deletePet";

    /**
     * 添加宠物
     */
    public static final String ADD_PET = "addPet";

    /**
     * 宠物ID
     */
    public static final String PET_ID = "petId";

    /**
     * 宠物名字
     */
    public static final String PET_NAME = "petName";

    /**
     * 宠物年龄
     */
    public static final String PET_AGE = "petAge";

    /**
     * 宠物种类
     */
    public static final String PET_TYPE = "petType";

    /**
     * 宠物性别
     */
    public static final String PET_SEX = "petSex";

    /**
     * 宠物重量
     */
    public static final String PET_WEIGHT = "petWeight";

    /**
     * 宠物状态
     */
    public static final String PET_INFO = "petInfo";

    /**
     * 绝育状态
     */
    public static final String PET_STERILIZATION = "petSterilization";

    /**
     * 等级
     */
    public static final String PET_LEVEL = "petLevel";

    /**
     * 驱虫日期
     */
    public static final String PET_EXPELLING_PARASITE_DATE = "petExpellingParasiteDate";

    /**
     * 宠物列表
     */
    public static final String PET_LIST = "petList";

    /**
     * 找商品列表
     */
    public static final String FIND_COMMODITY = "findCommodity";

    /**
     * 更新商品
     */
    public static final String UPDATE_COMMODITY = "updateCommodity";

    /**
     * 删除商品
     */
    public static final String DELETE_COMMODITY = "deleteCommodity";

    /**
     * 添加商品
     */
    public static final String ADD_COMMODITY = "addCommodity";

    /**
     * 商品Id
     */
    public static final String COMMODITY_ID = "commodityId";

    /**
     * 商品名字
     */
    public static final String COMMODITY_NAME = "commodityName";

    /**
     * 商品类别
     */
    public static final String COMMODITY_CATEGORY = "commodityCategory";

    /**
     * 商品列表
     */
    public static final String COMMODITY_LIST = "commodityList";

    /**
     * 商品类别列表
     */
    public static final String CATEGORY_LIST = "categoryList";

    /**
     * 价格
     */
    public static final String COMMODITY_PRICE = "commodityPrice";

    /**
     * 商品生产日期
     */
    public static final String COMMODITY_MANUFACTURE_DATE = "commodityManufactureDate";

    /**
     * 商品过期日期
     */
    public static final String COMMODITY_EXPIRATION_DATE = "commodityExpirationDate";

    /**
     * 商品数量
     */
    public static final String COMMODITY_SALES_NUM = "commoditySalesNum";

    /**
     * 商品介绍
     */
    public static final String COMMODITY_INFO = "commodityInfo";

    /**
     * 员工查询
     */
    public static final String FIND_EMP = "findEmp";

    /**
     * 更新员工数据
     */
    public static final String UPDATE_EMP = "updateEmp";

    /**
     * 添加员工
     */
    public static final String ADD_EMP = "addEmp";

    /**
     * 删除员工
     */
    public static final String DELETE_EMP = "deleteEmp";

    /**
     * 员工Id
     */
    private static final String EMP_ID = "empId";

    /**
     * 员工姓名
     */
    public static final String EMP_NAME = "empName";

    /**
     * 员工职位
     */
    public static final String EMP_ROLE = "empRole";

    /**
     * 员工性别
     */
    public static final String EMP_SEX = "empSex";

    /**
     * 员工生日
     */
    public static final String EMP_BIRTHERDAY = "empBirthday";

    /**
     * 员工年龄
     */
    public static final String EMP_AGE = "empAge";

    /**
     * 员工工资
     */
    public static final String EMP_SALARY = "empSalary";

    /**
     * 员工电话
     */
    public static final String EMP_PHONE = "empPhone";

    /**
     * 员工邮箱
     */
    public static final String EMP_EMAIL = "empEmail";

    /**
     * 员工列表
     */
    public static final String EMP_LIST = "empList";

    /**
     * 角色列表
     */
    public static final String ROLE_LIST = "roleList";

    /**
     * 订单查询
     */
    public static final String FIND_ORDER = "findOrder";

    /**
     * 添加订单
     */
    public static final String ADD_ORDER = "addOrder";

    /**
     * 更新订单
     */
    public static final String UPDATE_ORDER = "updateOrder";

    /**
     * 删除订单
     */
    public static final String DELETE_ORDER = "deleteOrder";

    /**
     * 订单Id
     */
    private static final String ORDER_ID = "orderId";

    /**
     * 订单列表
     */
    private static final String ORDER_LIST = "orderList";

    /**
     * 下单日期
     */
    public static final String ORDER_DATE = "orderDate";

    /**
     * 订单状态
     */
    public static final String ORDER_STATE = "orderState";

    /**
     * 订单商品数量
     */
    public static final String ORDER_COMMODITY_NUMBER = "orderCommodityNumber";

    /**
     * 非法操作
     */
    public static final String ERROR = "error";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入adminServlet...");

        String method = req.getParameter(METHOD);

        if (method == null) {
            method = "";
        }

        switch (method) {
            case UPDATE_USER:
                try {
                    updateUser(req, resp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case DELETE_USER:
                deleteUser(req, resp);
                break;
            case ADD_USER:
                addUser(req, resp);
                break;
            case FIND_PET:
                findPet(req, resp);
                break;
            case UPDATE_PET:
                updatePet(req, resp);
                break;
            case DELETE_PET:
                deletePet(req, resp);
                break;
            case ADD_PET:
                addPet(req, resp);
                break;
            case FIND_COMMODITY:
                findCommodity(req, resp);
                break;
            case UPDATE_COMMODITY:
                updateCommodity(req, resp);
                break;
            case DELETE_COMMODITY:
                deleteCommodity(req, resp);
                break;
            case ADD_COMMODITY:
                addCommodity(req, resp);
                break;
            case FIND_EMP:
                findEmp(req, resp);
                break;
            case UPDATE_EMP:
                updateEmp(req, resp);
                break;
            case ADD_EMP:
                addEmp(req, resp);
                break;
            case DELETE_EMP:
                deleteEmp(req, resp);
                break;
            case FIND_ORDER:
                findOrder(req, resp);
                break;
            case ADD_ORDER:
                addOrder(req, resp);
                break;
            case UPDATE_ORDER:
                updateOrder(req, resp);
                break;
            case DELETE_ORDER:
                deleteOrder(req, resp);
                break;
            default:
                findUserByName(req, resp);
        }
    }


    UserService userService = new UserServiceImpl();

    private void findUserByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usernameStr = req.getParameter(USER_NAME);
        int pageSize = ConstantsVal.PAGE_SIZE;
        int currentPageNo = 1;
        if (!StringUtils.isNullOrEmpty(req.getParameter("currentPageNo"))) {
            currentPageNo = Integer.parseInt(req.getParameter("currentPageNo"));
        }
        PageBean<User> userList = userService.findUserByName(usernameStr, pageSize, currentPageNo);
        req.setAttribute(USER_LIST, userList);
        req.setAttribute(MARK_FUN, "user");
        req.getRequestDispatcher(ConstantsRes.ADMIN_PAGE).forward(req, resp);
    }

    private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ParseException {
        String idStr = req.getParameter(UID);
        String usernameStr = req.getParameter(USER_NAME);
        String nameStr = req.getParameter(NAME);
        String passwordStr = req.getParameter(PASSWORD);
        String sexStr = req.getParameter(SEX);
        String emailStr = req.getParameter(EMAIL);
        String phoneStr = req.getParameter(PHONE);
        String registerDateStr = req.getParameter(REGISTER_DATE);
        String addressStr = req.getParameter(ADDRESS);
        String birthdayStr = req.getParameter(BIRTHDAY);
        String imageStr = req.getParameter(IMAGE);
        System.out.println(idStr);
        if (StringUtils.isNullOrEmpty(usernameStr)
                || StringUtils.isNullOrEmpty(passwordStr)
                || StringUtils.isNullOrEmpty(emailStr)
                || StringUtils.isNullOrEmpty(phoneStr)
                || StringUtils.isNullOrEmpty(registerDateStr)
                || StringUtils.isNullOrEmpty(birthdayStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=findUser").forward(req, resp);
            return;

        }
        Integer sexNum = 0;
        if (!StringUtils.isNullOrEmpty(sexStr) || sexStr.equals("男") || sexStr.equals("1")) {
            sexNum = 1;
        } else if (!StringUtils.isNullOrEmpty(sexStr) || sexStr.equals("女") || sexStr.equals("2")) {
            sexNum = 2;
        }
        userService.updateUser(
                User.builder()
                        .id(Integer.valueOf(idStr))
                        .username(usernameStr)
                        .name(nameStr)
                        .password(passwordStr)
                        .sex(sexNum).email(emailStr)
                        .phoneNum(phoneStr)
                        .registerDate(new SimpleDateFormat("yyyy-MM-dd").parse(registerDateStr))
                        .address(addressStr)
                        .birthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthdayStr))
                        .image(imageStr)
                        .build());
        req.getRequestDispatcher("/admin?method=findUser").forward(req, resp);
    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = req.getParameter(UID);
        userService.deleteUser(Integer.parseInt(idStr));
        req.getRequestDispatcher("/admin?method=findUser").forward(req, resp);
    }

    private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usernameStr = req.getParameter(USER_NAME);
        String nameStr = req.getParameter(NAME);
        String passwordStr = req.getParameter(PASSWORD);
        String sexStr = req.getParameter(SEX);
        String emailStr = req.getParameter(EMAIL);
        String phoneStr = req.getParameter(PHONE);
        String registerDateStr = req.getParameter(REGISTER_DATE);
        String addressStr = req.getParameter(ADDRESS);
        String birthdayStr = req.getParameter(BIRTHDAY);
        String imageStr = req.getParameter(IMAGE);
        if (StringUtils.isNullOrEmpty(usernameStr)
                || StringUtils.isNullOrEmpty(passwordStr)
                || StringUtils.isNullOrEmpty(emailStr)
                || StringUtils.isNullOrEmpty(phoneStr)
                || StringUtils.isNullOrEmpty(registerDateStr)
                || StringUtils.isNullOrEmpty(birthdayStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=findUser").forward(req, resp);
            return;
        }
        Integer sexNum = 0;
        if (!StringUtils.isNullOrEmpty(sexStr)) {
            if (sexStr.equals("男")) {
                sexNum = 1;
            } else if (sexStr.equals("女")) {
                sexNum = 2;
            }
        }
        try {
            userService.addUser(User.builder()
                    .username(usernameStr)
                    .name(nameStr)
                    .password(passwordStr)
                    .sex(sexNum).
                    email(emailStr)
                    .phoneNum(phoneStr)
                    .registerDate(new SimpleDateFormat("yyyy-MM-dd").parse(registerDateStr))
                    .address(addressStr)
                    .birthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthdayStr))
                    .image(imageStr)
                    .build());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        req.getRequestDispatcher("/admin?method=findUser").forward(req, resp);
    }


    PetService petService = new PetServiceImpl();

    private void findPet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String petNameStr = req.getParameter(PET_NAME);
        int pageSize = ConstantsVal.PAGE_SIZE;
        int currentPageNo = 1;
        if (!StringUtils.isNullOrEmpty(req.getParameter("currentPageNo"))) {
            currentPageNo = Integer.parseInt(req.getParameter("currentPageNo"));
        }
        PageBean<Pet> petList = petService.findPetByName(petNameStr, pageSize, currentPageNo);
        req.setAttribute(PET_LIST, petList);
        req.setAttribute(MARK_FUN, "pet");
        req.getRequestDispatcher(ConstantsRes.ADMIN_PAGE).forward(req, resp);
    }

    private void updatePet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String petIdStr = req.getParameter(PET_ID);
        String petNameStr = req.getParameter(PET_NAME);
        String petAgeStr = req.getParameter(PET_AGE);
        String petTypeStr = req.getParameter(PET_TYPE);
        String petSexStr = req.getParameter(PET_SEX);
        String petWightStr = req.getParameter(PET_WEIGHT);
        String petInfoStr = req.getParameter(PET_INFO);
        String petSterilizationStr = req.getParameter(PET_STERILIZATION);
        String petLevelStr = req.getParameter(PET_LEVEL);
        String petExpellingParasiteDateStr = req.getParameter(PET_EXPELLING_PARASITE_DATE);
        String petUidStr = req.getParameter(UID);
        if (StringUtils.isNullOrEmpty(petLevelStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        if (!StringUtils.isNullOrEmpty(petExpellingParasiteDateStr)) {
            try {
                date = simpleDateFormat.parse(petExpellingParasiteDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        petService.updatePet(Pet.builder()
                .id(Integer.valueOf(petIdStr))
                .name(petNameStr)
                .age(Integer.valueOf(petAgeStr))
                .petType(petTypeStr)
                .sex(Integer.valueOf(petSexStr))
                .weight(Double.valueOf(petWightStr))
                .info(petInfoStr)
                .level(Integer.valueOf(petLevelStr))
                .sterilization(petSterilizationStr)
                .expellingParasiteDate(date)
                .userId(Integer.valueOf(petUidStr))
                .build());
        req.getRequestDispatcher("/admin?method=findPet").forward(req, resp);
    }

    private void deletePet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = req.getParameter(PET_ID);
        petService.delPet(Integer.parseInt(idStr));
        req.getRequestDispatcher("/admin?method=findPet").forward(req, resp);
    }

    private void addPet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String petNameStr = req.getParameter(PET_NAME);
        String petAgeStr = req.getParameter(PET_AGE);
        String petTypeStr = req.getParameter(PET_TYPE);
        String petSexStr = req.getParameter(PET_SEX);
        String petWightStr = req.getParameter(PET_WEIGHT);
        String petInfoStr = req.getParameter(PET_INFO);
        String petSterilizationStr = req.getParameter(PET_STERILIZATION);
        String petLevelStr = req.getParameter(PET_LEVEL);
        String petExpellingParasiteDateStr = req.getParameter(PET_EXPELLING_PARASITE_DATE);
        String petUidStr = req.getParameter(UID);
        if (StringUtils.isNullOrEmpty(petLevelStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        if (!StringUtils.isNullOrEmpty(petExpellingParasiteDateStr)) {
            try {
                date = simpleDateFormat.parse(petExpellingParasiteDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        petService.addPet(Integer.parseInt(petUidStr), Pet.builder()
                .name(petNameStr)
                .age(Integer.valueOf(petAgeStr))
                .petType(petTypeStr)
                .sex(Integer.valueOf(petSexStr))
                .weight(Double.valueOf(petWightStr))
                .info(petInfoStr)
                .level(Integer.valueOf(petLevelStr))
                .sterilization(petSterilizationStr)
                .expellingParasiteDate(date)
                .build());
        req.getRequestDispatcher("/admin?method=findPet").forward(req, resp);
    }


    CommodityService commodityService = new CommodityServiceImpl();

    private void findCommodity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityNameStr = req.getParameter(COMMODITY_NAME);
        String commodityCategory = req.getParameter(COMMODITY_CATEGORY);
        int CategoryId = 0;
        CategoryService categoryService = new CategoryServiceImpl();
        List<Category> categoryList = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(commodityCategory)) {
            categoryList = categoryService.getCategory(Integer.parseInt(commodityCategory));
            CategoryId = categoryList.get(0).getId();
        } else {
            categoryList = categoryService.getCategory(CategoryId);
        }
        int currentPageNo = 1;
        if (!StringUtils.isNullOrEmpty(req.getParameter("currentPageNo"))) {
            currentPageNo = Integer.parseInt(req.getParameter("currentPageNo"));
        }
        PageBean<Commodity> commodityList = commodityService.findCommodityList(commodityNameStr, CategoryId, currentPageNo, ConstantsVal.PAGE_SIZE);
        req.setAttribute(COMMODITY_LIST, commodityList);
        req.setAttribute(MARK_FUN, "commodity");
        req.setAttribute(CATEGORY_LIST, categoryList);
        req.getRequestDispatcher(ConstantsRes.ADMIN_PAGE).forward(req, resp);
    }

    private void updateCommodity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityIdStr = req.getParameter(COMMODITY_ID);
        String commodityNameStr = req.getParameter(COMMODITY_NAME);
        String category = req.getParameter(COMMODITY_CATEGORY);
        String commodityPriceStr = req.getParameter(COMMODITY_PRICE);
        String commodityManufactureDateStr = req.getParameter(COMMODITY_MANUFACTURE_DATE);
        String commodityExpirationDateStr = req.getParameter(COMMODITY_EXPIRATION_DATE);
        String commoditySalesNumStr = req.getParameter(COMMODITY_SALES_NUM);
        String commodityInfo = req.getParameter(COMMODITY_INFO);
        if (StringUtils.isNullOrEmpty(commodityNameStr)
                || StringUtils.isNullOrEmpty(commodityPriceStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date ExpirationDate = null;
        Date ManufactureDate = null;
        if (!StringUtils.isNullOrEmpty(commodityExpirationDateStr)) {
            try {
                ExpirationDate = simpleDateFormat.parse(commodityExpirationDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isNullOrEmpty(commodityManufactureDateStr)) {
            try {
                ManufactureDate = simpleDateFormat.parse(commodityManufactureDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        commodityService.updateCommodity(Commodity.builder()
                .id(Integer.valueOf(commodityIdStr))
                .name(commodityNameStr)
                .price(Double.valueOf(commodityPriceStr))
                .manufactureDate(ManufactureDate)
                .expirationDate(ExpirationDate)
                .salesNum(Integer.valueOf(commoditySalesNumStr))
                .info(commodityInfo).build(), Integer.parseInt(category));
        req.getRequestDispatcher("/admin?method=findCommodity").forward(req, resp);
    }

    private void deleteCommodity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityIdStr = req.getParameter(COMMODITY_ID);
        commodityService.deleteCommodity(Integer.parseInt(commodityIdStr));
        req.getRequestDispatcher("/admin?method=findCommodity").forward(req, resp);

    }

    private void addCommodity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityNameStr = req.getParameter(COMMODITY_NAME);
        String category = req.getParameter(COMMODITY_CATEGORY);
        String commodityPriceStr = req.getParameter(COMMODITY_PRICE);
        String commodityManufactureDateStr = req.getParameter(COMMODITY_MANUFACTURE_DATE);
        String commodityExpirationDateStr = req.getParameter(COMMODITY_EXPIRATION_DATE);
        String commoditySalesNumStr = req.getParameter(COMMODITY_SALES_NUM);
        String commodityInfo = req.getParameter(COMMODITY_INFO);
        if (StringUtils.isNullOrEmpty(commodityNameStr)
                || StringUtils.isNullOrEmpty(commodityPriceStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date ExpirationDate = null;
        Date ManufactureDate = null;
        if (!StringUtils.isNullOrEmpty(commodityExpirationDateStr)) {
            try {
                ExpirationDate = simpleDateFormat.parse(commodityExpirationDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (!StringUtils.isNullOrEmpty(commodityManufactureDateStr)) {
            try {
                ManufactureDate = simpleDateFormat.parse(commodityManufactureDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        commodityService.addCommodity(Commodity.builder()
                .name(commodityNameStr)
                .price(Double.valueOf(commodityPriceStr))
                .manufactureDate(ManufactureDate)
                .expirationDate(ExpirationDate)
                .salesNum(Integer.valueOf(commoditySalesNumStr))
                .info(commodityInfo).build(), Integer.parseInt(category));
        req.getRequestDispatcher("/admin?method=findCommodity").forward(req, resp);
    }

    EmpService empService = new EmpServiceImpl();

    private void findEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empNameStr = req.getParameter(EMP_NAME);
        String empRoleStr = req.getParameter(EMP_ROLE);
        RoleService roleService = new RoleServiceImpl();
        int empRoleId = 0;
        List<Role> roleList = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(empRoleStr)) {
            roleList = roleService.findAllRoleList(Integer.parseInt(empRoleStr));
            empRoleId = roleList.get(0).getId();
        } else {
            roleList = roleService.findAllRoleList(empRoleId);
        }
        int currentPageNo = 1;
        if (!StringUtils.isNullOrEmpty(req.getParameter("currentPageNo"))) {
            currentPageNo = Integer.parseInt(req.getParameter("currentPageNo"));
        }
        PageBean<Emp> empPageBean = empService.findEmpList(empNameStr, empRoleId, currentPageNo, ConstantsVal.PAGE_SIZE);
        for (Emp emp : empPageBean.getContent()) {
            List<Boolean> roleBool = new ArrayList<>();
            List<Integer> empRoleIds = new ArrayList<>();
            for (Role role : emp.getRoleList()) {
                empRoleIds.add(role.getId());
            }
            for (int i = 0; i < roleList.size(); i++) {
                roleBool.add(empRoleIds.contains(roleList.get(i).getId()));
            }
            emp.setRoleBool(roleBool);
        }
        System.out.println(empPageBean);
        req.setAttribute(MARK_FUN, "emp");
        req.setAttribute(ROLE_LIST, roleList);
        req.setAttribute(EMP_LIST, empPageBean);
        req.getRequestDispatcher(ConstantsRes.ADMIN_PAGE).forward(req, resp);
    }

    private void updateEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empIdStr = req.getParameter(EMP_ID);
        String empNameStr = req.getParameter(EMP_NAME);
        String empRoleStr = req.getParameter("selectValue");
        String empSexStr = req.getParameter(EMP_SEX);
        String empBirthdayStr = req.getParameter(EMP_BIRTHERDAY);
        String empAgeStr = req.getParameter(EMP_AGE);
        String empSalaryStr = req.getParameter(EMP_SALARY);
        String empPhoneStr = req.getParameter(EMP_PHONE);
        String empEmailStr = req.getParameter(EMP_EMAIL);
        if (StringUtils.isNullOrEmpty(empNameStr)
                || StringUtils.isNullOrEmpty(empRoleStr)
                || StringUtils.isNullOrEmpty(empSexStr)
                || StringUtils.isNullOrEmpty(empAgeStr)
                || StringUtils.isNullOrEmpty(empSalaryStr)
                || StringUtils.isNullOrEmpty(empPhoneStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        List<Integer> roleId = new ArrayList<>();
        for (int i = 0; i < empRoleStr.length(); i++) {
            if (empRoleStr.charAt(i) == ':') {
                roleId.add(Character.getNumericValue(empRoleStr.charAt(i - 1)));
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthdayDate = null;
        if (!StringUtils.isNullOrEmpty(empBirthdayStr)) {
            try {
                birthdayDate = simpleDateFormat.parse(empBirthdayStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        empService.updateEmp(Emp.builder()
                .id(Integer.valueOf(empIdStr))
                .name(empNameStr)
                .sex(empSexStr)
                .birthday(birthdayDate)
                .age(Integer.valueOf(empAgeStr))
                .salary(Double.valueOf(empSalaryStr))
                .phoneNum(empPhoneStr)
                .email(empEmailStr).build(), roleId);
        req.getRequestDispatcher("/admin?method=findEmp").forward(req, resp);
    }

    private void addEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empNameStr = req.getParameter(EMP_NAME);
        String empRoleStr = req.getParameter("selectValue");
        String empSexStr = req.getParameter(EMP_SEX);
        String empBirthdayStr = req.getParameter(EMP_BIRTHERDAY);
        String empAgeStr = req.getParameter(EMP_AGE);
        String empSalaryStr = req.getParameter(EMP_SALARY);
        String empPhoneStr = req.getParameter(EMP_PHONE);
        String empEmailStr = req.getParameter(EMP_EMAIL);
        if (StringUtils.isNullOrEmpty(empNameStr)
                || StringUtils.isNullOrEmpty(empRoleStr)
                || StringUtils.isNullOrEmpty(empSexStr)
                || StringUtils.isNullOrEmpty(empAgeStr)
                || StringUtils.isNullOrEmpty(empSalaryStr)
                || StringUtils.isNullOrEmpty(empPhoneStr)) {
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        List<Integer> roleId = new ArrayList<>();
        for (int i = 0; i < empRoleStr.length(); i++) {
            if (empRoleStr.charAt(i) == ':') {
                roleId.add(Character.getNumericValue(empRoleStr.charAt(i - 1)));
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthdayDate = null;
        if (!StringUtils.isNullOrEmpty(empBirthdayStr)) {
            try {
                birthdayDate = simpleDateFormat.parse(empBirthdayStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        empService.addEmp(Emp.builder()
                .name(empNameStr)
                .sex(empSexStr)
                .birthday(birthdayDate)
                .age(Integer.valueOf(empAgeStr))
                .salary(Double.valueOf(empSalaryStr))
                .phoneNum(empPhoneStr)
                .email(empEmailStr).build(), roleId);
        req.getRequestDispatcher("/admin?method=findEmp").forward(req, resp);
    }

    private void deleteEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empIdStr = req.getParameter(EMP_ID);
        empService.deleteEmpAndAdminUserByEmpId(Integer.parseInt(empIdStr));
        req.getRequestDispatcher("/admin?method=findEmp").forward(req, resp);
    }

    private void findOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();
        String orderIdStr = req.getParameter(ORDER_ID);
        int currentPageNo = 1;
        if (!StringUtils.isNullOrEmpty(req.getParameter("currentPageNo"))) {
            currentPageNo = Integer.parseInt(req.getParameter("currentPageNo"));
        }
        if (StringUtils.isNullOrEmpty(orderIdStr)) {
            PageBean<Order> orderPageBean = orderService.findOrderList(currentPageNo, ConstantsVal.PAGE_SIZE);
            req.setAttribute(ORDER_LIST, orderPageBean);
        } else {
            Order order = orderService.findOrderById(Integer.parseInt(orderIdStr));
            ArrayList<Order> orders = new ArrayList<>();
            orders.add(order);

            req.setAttribute(ORDER_LIST, PageBean.<Order>builder()
                    .content(orders)
                    .pageSize(1)
                    .elementTotalCount(1)
                    .currentPageNo(1)
                    .totalPageCount(1)
                    .totalCount(1)
                    .build());
        }
        req.setAttribute(MARK_FUN,"order");
        req.getRequestDispatcher(ConstantsRes.ADMIN_PAGE).forward(req, resp);
    }

    private void addOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();
        String orderDateStr = req.getParameter(ORDER_DATE);
        String orderCIdStr = req.getParameter(COMMODITY_ID);
        String orderUIdStr = req.getParameter(UID);
        String orderStateStr = req.getParameter(ORDER_STATE);
        String orderComNumStr = req.getParameter(ORDER_COMMODITY_NUMBER);
        if (StringUtils.isNullOrEmpty(orderDateStr)
                ||StringUtils.isNullOrEmpty(orderStateStr)
                ||StringUtils.isNullOrEmpty(ORDER_COMMODITY_NUMBER)
                ||StringUtils.isNullOrEmpty(orderCIdStr)
                ||StringUtils.isNullOrEmpty(orderUIdStr)
                ||StringUtils.isNullOrEmpty(orderComNumStr)){
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = null;
        if (!StringUtils.isNullOrEmpty(orderDateStr)) {
            try {
                orderDate = simpleDateFormat.parse(orderDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        orderService.addOrder(Order.builder()
                .ordersDate(orderDate)
                .state(Integer.valueOf(orderStateStr))
                .comNum(Integer.parseInt(orderComNumStr))
                .build()
                , Integer.parseInt(orderUIdStr)
                , Integer.parseInt(orderCIdStr));
        req.getRequestDispatcher("/admin?method=findOrder").forward(req, resp);
    }

    private void updateOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();
        String orderIdStr = req.getParameter(ORDER_ID);
        String orderDateStr = req.getParameter(ORDER_DATE);
        String orderCIdStr = req.getParameter(COMMODITY_ID);
        String orderUIdStr = req.getParameter(UID);
        String orderStateStr = req.getParameter(ORDER_STATE);
        String orderComNumStr = req.getParameter(ORDER_COMMODITY_NUMBER);
        if (StringUtils.isNullOrEmpty(orderDateStr)
                ||StringUtils.isNullOrEmpty(orderStateStr)
                ||StringUtils.isNullOrEmpty(ORDER_COMMODITY_NUMBER)
                ||StringUtils.isNullOrEmpty(orderCIdStr)
                ||StringUtils.isNullOrEmpty(orderUIdStr)
                ||StringUtils.isNullOrEmpty(orderComNumStr)){
            req.setAttribute(ERROR, "非法操作");
            req.getRequestDispatcher("/admin?method=error").forward(req, resp);
            return;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = null;
        if (!StringUtils.isNullOrEmpty(orderDateStr)) {
            try {
                orderDate = simpleDateFormat.parse(orderDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        orderService.updateOrder(Order.builder()
                        .id(Integer.valueOf(orderIdStr))
                        .ordersDate(orderDate)
                        .state(Integer.valueOf(orderStateStr))
                        .comNum(Integer.parseInt(orderComNumStr))
                        .build()
                , Integer.parseInt(orderUIdStr)
                , Integer.parseInt(orderCIdStr));
        req.getRequestDispatcher("/admin?method=findOrder").forward(req, resp);
    }

    private void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();
        String orderIdStr = req.getParameter(ORDER_ID);
        orderService.deleteOrderByOid(Integer.parseInt(orderIdStr));
        req.getRequestDispatcher("/admin?method=findOrder").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
